package com.thunder.ktv.scoreengine2test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.thunder.ktv.scoreengine2sdk.DifficultyLevel;
import com.thunder.ktv.scoreengine2sdk.ScoreDimension;
import com.thunder.ktv.scoreengine2sdk.ScoreEngine2;
import com.thunder.ktv.scoreengine2sdk.SongStyle;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // 权限请求码
    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final int MANAGE_STORAGE_PERMISSION_REQUEST_CODE = 101;
    
    // 需要请求的权限数组
    private String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO
    };

    private ListView listViewSongs;
    private Button btnStartScore;
    private Button btnSaveConfig;
    private Button btnShowTV;
    private List<Song> songList;
    private SongAdapter songAdapter;
    private Song selectedSong;
    
    // 配置界面相关控件
    private Spinner spinnerSongStyle;
    private Spinner spinnerDifficulty;
    private CheckBox checkboxPitch;
    private CheckBox checkboxRhythm;
    private CheckBox checkboxBrightness;
    private CheckBox checkboxEmotion;
    private CheckBox checkboxBreath;
    private CheckBox checkboxTimbre;
    
    // 评分引擎配置
    private ScoreEngine2.ScoreEngineConfig scoreEngineConfig;
    
    // SharedPreferences 用于保存配置
    private SharedPreferences preferences;
    private static final String PREF_NAME = "ScoreEnginePrefs";
    private static final String KEY_SONG_STYLE = "song_style";
    private static final String KEY_DIFFICULTY = "difficulty";
    private static final String KEY_DIMENSIONS = "dimensions";

    private boolean showTV = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 初始化SharedPreferences
        preferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        
        // 请求权限
        requestPermissions();
        
        // 初始化视图
        initViews();
        
        // 初始化数据
        initData();
        
        // 设置监听器
        setupListeners();
        
        // 初始化评分引擎配置
        initScoreEngineConfig();
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        // 歌曲列表
        listViewSongs = findViewById(R.id.listViewSongs);
        btnStartScore = findViewById(R.id.btnStartScore);
        
        // 配置界面
        spinnerSongStyle = findViewById(R.id.spinnerSongStyle);
        spinnerDifficulty = findViewById(R.id.spinnerDifficulty);
        checkboxPitch = findViewById(R.id.checkboxPitch);
        checkboxRhythm = findViewById(R.id.checkboxRhythm);
        checkboxBrightness = findViewById(R.id.checkboxBrightness);
        checkboxEmotion = findViewById(R.id.checkboxEmotion);
        checkboxBreath = findViewById(R.id.checkboxBreath);
        checkboxTimbre = findViewById(R.id.checkboxTimbre);
        btnSaveConfig = findViewById(R.id.btnSaveConfig);
        btnShowTV = findViewById(R.id.showTV);
        if(showTV){
            btnShowTV.setText("双屏模式");
        }else{
            btnShowTV.setText("单屏模式");
        }
        // 初始化下拉选择器
        setupSpinners();
    }
    
    /**
     * 初始化下拉选择器
     */
    private void setupSpinners() {
        // 歌曲风格下拉选择器
        String[] songStyles = new String[SongStyle.values().length];
        for (int i = 0; i < SongStyle.values().length; i++) {
            songStyles[i] = SongStyle.values()[i].getChineseName();
        }
        ArrayAdapter<String> styleAdapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, songStyles);
        styleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSongStyle.setAdapter(styleAdapter);
        
        // 难度等级下拉选择器
        String[] difficultyLevels = new String[DifficultyLevel.values().length];
        for (int i = 0; i < DifficultyLevel.values().length; i++) {
            difficultyLevels[i] = DifficultyLevel.values()[i].getChineseName();
        }
        ArrayAdapter<String> difficultyAdapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, difficultyLevels);
        difficultyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerDifficulty.setAdapter(difficultyAdapter);
    }


    void addSong(Song song)
    {
        if(song.isValid()){
            songList.add(song);
        }
    }
    /**
     * 初始化数据
     */
    private void initData() {
        // 创建歌曲列表
        songList = new ArrayList<>();
//        addSong(new Song(7022619, "十年", "陈奕迅"));
//        addSong(new Song(6006213, "痒", "黄龄"));
        addSong(new Song(7553043, "成都(HD)", "赵雷"));
        addSong(new Song(7544252, "漂洋过海来看你", "李宗盛"));
        addSong(new Song(7131735, "一千个伤心的理由(HD)", "张学友"));
        addSong(new Song(7000948, "过火(HD)", "张信哲"));
        addSong(new Song(7113312, "搀扶(HD)", "马健涛"));
        addSong(new Song(7300616, "后来(HD)", "刘若英"));
        addSong(new Song(7423524, "红尘情歌(HD)", "高安"));
        addSong(new Song(7401487, "我的好兄弟(HD)", "小沈阳"));
        addSong(new Song(7593272, "我是真的爱上你(B)(HD)", "王杰"));
        addSong(new Song(7593118, "十年(B)", "陈奕迅"));
        addSong(new Song(7008150, "水手(HD)", "郑智化"));
        addSong(new Song(7593380, "突然的自我(B)(HD)", "伍佰"));
        addSong(new Song(7026522, "挪威的森林(HD)", "伍佰"));
        addSong(new Song(7593099, "西海情歌(HD)", "刀郎"));
        addSong(new Song(8012556, "演员(HD)", "薛之谦"));
        addSong(new Song(7019464, "朋友(HD)", "周华健"));
        addSong(new Song(7013785, "大海(HD)", "张雨生"));
        addSong(new Song(8014396, "再见只是陌生人(HD)", "庄心妍"));
        addSong(new Song(7404225, "奢香夫人(HD)", "凤凰传奇"));
        addSong(new Song(7403328, "朋友的酒(HD)", "李晓杰"));
        addSong(new Song(7022413, "苹果香(HD)", "黑大婶回乡带娃"));
        addSong(new Song(7500052, "海阔天空(HD)", "Beyond"));
        addSong(new Song(7014032, "留什么给你(HD)", "孙楠"));
        addSong(new Song(7408057, "素颜(HD)", "许嵩"));
        addSong(new Song(7650021, "晴天", "周杰伦"));
        addSong(new Song(7593403, "可可托海的牧羊人(HD)", "王琪"));
        addSong(new Song(7593427, "爱如潮水(B)", "张信哲"));
        addSong(new Song(8605389, "听闻远方有你(HD)", "刘艺雯"));
        addSong(new Song(7124709, "知心爱人(HD)", "任静"));
        addSong(new Song(7429206, "花桥流水(HD)", "高安"));
        addSong(new Song(7027347, "我怀念的(HD)", "孙燕姿"));
        addSong(new Song(7545063, "成都-歌手(HD)", "赵雷"));
        addSong(new Song(8006777, "特别的人(HD)", "方大同"));
        addSong(new Song(7593450, "黄昏(B)(HD)", "周传雄"));
        addSong(new Song(7593088, "冲动的惩罚(B)(HD)", "刀郎"));
        addSong(new Song(7409832, "因为爱情(HD)", "陈奕迅"));
        addSong(new Song(8625874, "爱你一万年(DJ版)(HD)", "花姐"));
        addSong(new Song(7402676, "背对背拥抱(HD)", "林俊杰"));
        addSong(new Song(7408647, "老男孩(HD)", "筷子兄弟"));
        addSong(new Song(8933799, "如果爱忘了(HD)", "汪苏泷"));
        addSong(new Song(7402766, "最炫民族风(HD)", "凤凰传奇"));
        addSong(new Song(7593231, "泡沫(B)", "邓紫棋"));
        addSong(new Song(7132135, "江南(HD)", "林俊杰"));
        addSong(new Song(7036002, "爱错", "王力宏"));
        addSong(new Song(7405033, "偏爱(HD)", "张芸京"));
        addSong(new Song(7416533, "红色高跟鞋(HD)", "蔡健雅"));
        addSong(new Song(7132227, "青花(HD)", "周传雄"));
        addSong(new Song(7594460, "红唇(HD)", "王峰"));
        addSong(new Song(7114979, "别怕我伤心(HD)", "张信哲"));
        addSong(new Song(7032871, "军中绿花(HD)", "小曾"));
        addSong(new Song(7131472, "当爱在靠近(HD)", "刘若英"));
        addSong(new Song(7300433, "萍聚(HD)", "卓依婷"));
        addSong(new Song(7012792, "一路向北(HD)", "周杰伦"));
        addSong(new Song(7100966, "跳楼机(HD)", "LBI利比"));
        addSong(new Song(7407316, "包容(授权版)", "郑源"));
        addSong(new Song(7014571, "光辉岁月(HD)", "Beyond"));
        addSong(new Song(7571336, "陷阱(HD)", "王北车"));
        addSong(new Song(7039911, "月半小夜曲(HD)", "陈慧娴"));
        addSong(new Song(7599910, "最后的人(HD)", "杨小壮"));
        addSong(new Song(7104793, "稻香(HD)", "周杰伦"));
        addSong(new Song(7012491, "单身情歌(HD)", "林志炫"));
        addSong(new Song(7300629, "甘心情愿(HD)", "郭峰"));
        addSong(new Song(7300835, "美丽的神话(HD)", "孙楠"));
        addSong(new Song(8895173, "情罪(HD)", "陈瑞"));
        addSong(new Song(7402764, "全是爱(HD)", "凤凰传奇"));
        addSong(new Song(8625226, "红颜知己(HD)", "王峰"));
        addSong(new Song(7132191, "搁浅(HD)", "周杰伦"));
        addSong(new Song(8867380, "唯一(HD)", "邓紫棋"));
        addSong(new Song(8602189, "如愿(HD)", "王菲"));
        addSong(new Song(8002135, "修炼爱情(HD)", "林俊杰"));
        addSong(new Song(7300093, "青花瓷(HD)", "周杰伦"));
        addSong(new Song(7038814, "我只在乎你(HD)", "邓丽君"));
        addSong(new Song(7200258, "伤心太平洋(HD)", "任贤齐"));
        addSong(new Song(7095550, "童年老家(HD)", "马健涛"));
        addSong(new Song(7200081, "盛夏的果实(HD)", "莫文蔚"));
        addSong(new Song(7041694, "天下(HD)", "张杰==大陆"));
        addSong(new Song(8001948, "闯码头(HD)", "大哲"));
        addSong(new Song(7523910, "告白气球(HD)", "周杰伦"));
        addSong(new Song(7652418, "讲不出再见(HD)", "谭咏麟"));
        addSong(new Song(7122369, "曾经心痛(HD)", "叶倩文"));
        addSong(new Song(7560958, "体面(HD)", "于文文"));
        addSong(new Song(7300654, "童话(HD)", "光良"));
        addSong(new Song(7101068, "先说爱的人为什么先离开(HD)", "田园"));
        addSong(new Song(7002477, "痴心绝对(HD)", "李圣杰"));
        addSong(new Song(7300389, "女儿情(HD)", "吴静"));
        addSong(new Song(7548187, "男孩-歌手(HD)", "梁博"));
        addSong(new Song(7350026, "小酒窝(HD)", "林俊杰"));
        addSong(new Song(7007208, "精忠报国(HD)", "屠洪刚"));
        addSong(new Song(7104794, "说好的幸福呢(HD)", "周杰伦"));
        addSong(new Song(7030232, "有多少爱可以重来(HD)", "迪克牛仔"));
        addSong(new Song(7072740, "凡人歌(HD)", "半吨兄弟"));
        addSong(new Song(8679456, "放纵(HD)", "怪阿姨"));
        addSong(new Song(7407907, "Always Online(HD)", "林俊杰"));
        addSong(new Song(8001716, "明明就(HD)", "周杰伦"));
        addSong(new Song(8010056, "可惜没如果(HD)", "林俊杰"));
        addSong(new Song(7132071, "你(HD)", "屠洪刚"));
        addSong(new Song(8884639, "西楼儿女(HD)", "岳云鹏"));

        // 设置适配器
        songAdapter = new SongAdapter(this, songList);
        listViewSongs.setAdapter(songAdapter);

        // 默认选中第一首歌
        if (!songList.isEmpty()) {
            selectedSong = songList.get(0);
            listViewSongs.setItemChecked(0, true);
        }
    }

    /**
     * 初始化评分引擎配置
     */
    private void initScoreEngineConfig() {
        // 创建默认配置
        scoreEngineConfig = ScoreEngine2.ScoreEngineConfig.createDefault();
        
        // 从SharedPreferences加载保存的配置
        int songStyleValue = preferences.getInt(KEY_SONG_STYLE, SongStyle.POP.getValue());
        int difficultyValue = preferences.getInt(KEY_DIFFICULTY, DifficultyLevel.NORMAL.getValue());
        int dimensionsValue = preferences.getInt(KEY_DIMENSIONS, ScoreDimension.ALL.getValue());
        
        // 设置保存的配置
        scoreEngineConfig.style = SongStyle.fromValue(songStyleValue);
        scoreEngineConfig.difficulty = DifficultyLevel.fromValue(difficultyValue);
        scoreEngineConfig.enabledDimensions = dimensionsValue;
        
        // 更新UI显示
        updateUIFromConfig();
    }
    
    /**
     * 根据配置更新UI显示
     */
    private void updateUIFromConfig() {
        // 设置歌曲风格
        spinnerSongStyle.setSelection(scoreEngineConfig.style.getValue());
        
        // 设置难度等级
        spinnerDifficulty.setSelection(scoreEngineConfig.difficulty.getValue());
        
        // 设置评分维度
        checkboxPitch.setChecked(ScoreDimension.PITCH.isEnabled(scoreEngineConfig.enabledDimensions));
        checkboxRhythm.setChecked(ScoreDimension.RHYTHM.isEnabled(scoreEngineConfig.enabledDimensions));
        checkboxBrightness.setChecked(ScoreDimension.BRIGHTNESS.isEnabled(scoreEngineConfig.enabledDimensions));
        checkboxEmotion.setChecked(ScoreDimension.EMOTION.isEnabled(scoreEngineConfig.enabledDimensions));
        checkboxBreath.setChecked(ScoreDimension.BREATH.isEnabled(scoreEngineConfig.enabledDimensions));
        checkboxTimbre.setChecked(ScoreDimension.TIMBRE.isEnabled(scoreEngineConfig.enabledDimensions));
    }
    
    /**
     * 从UI控件更新配置
     */
    private void updateConfigFromUI() {
        // 更新歌曲风格
        scoreEngineConfig.style = SongStyle.values()[spinnerSongStyle.getSelectedItemPosition()];
        
        // 更新难度等级
        scoreEngineConfig.difficulty = DifficultyLevel.values()[spinnerDifficulty.getSelectedItemPosition()];
        
        // 更新评分维度
        List<ScoreDimension> enabledDimensions = new ArrayList<>();
        
        if (checkboxPitch.isChecked()) {
            enabledDimensions.add(ScoreDimension.PITCH);
        }
        
        if (checkboxRhythm.isChecked()) {
            enabledDimensions.add(ScoreDimension.RHYTHM);
        }
        
        if (checkboxBrightness.isChecked()) {
            enabledDimensions.add(ScoreDimension.BRIGHTNESS);
        }
        
        if (checkboxEmotion.isChecked()) {
            enabledDimensions.add(ScoreDimension.EMOTION);
        }
        
        if (checkboxBreath.isChecked()) {
            enabledDimensions.add(ScoreDimension.BREATH);
        }
        
        if (checkboxTimbre.isChecked()) {
            enabledDimensions.add(ScoreDimension.TIMBRE);
        }
        
        ScoreDimension[] dimensions = enabledDimensions.toArray(new ScoreDimension[0]);
        scoreEngineConfig.enabledDimensions = ScoreDimension.combine(dimensions);
    }
    
    /**
     * 保存配置到SharedPreferences
     */
    private void saveConfigToPreferences() {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(KEY_SONG_STYLE, scoreEngineConfig.style.getValue());
        editor.putInt(KEY_DIFFICULTY, scoreEngineConfig.difficulty.getValue());
        editor.putInt(KEY_DIMENSIONS, scoreEngineConfig.enabledDimensions);
        editor.apply();
        
        Toast.makeText(this, "配置已保存", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 设置监听器
     */
    private void setupListeners() {
        // 列表项点击监听
        listViewSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectedSong = songList.get(position);
                songAdapter.notifyDataSetChanged();
            }
        });
        
        // "开始打分"按钮点击监听
        btnStartScore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedSong != null) {
                    // 更新配置
                    updateConfigFromUI();
                    
                    // 跳转到打分界面
                    Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
                    intent.putExtra("selected_song", selectedSong);
                    intent.putExtra("score_engine_config", createSerializableConfig());
                    intent.putExtra("showTV", showTV);
                    startActivity(intent);
                } else {
                    Toast.makeText(MainActivity.this, "请先选择一首歌曲", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        // "保存配置"按钮点击监听
        btnSaveConfig.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateConfigFromUI();
                saveConfigToPreferences();
            }
        });
        btnShowTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTV = !showTV;
                if(showTV){
                    btnShowTV.setText("双屏模式");
                }else{
                    btnShowTV.setText("单屏模式");
                }
            }
        });
    }
    
    /**
     * 创建可序列化的配置对象，用于传递给打分界面
     */
    private ScoreEngineConfig createSerializableConfig() {
        ScoreEngineConfig config = new ScoreEngineConfig();
        config.songStyle = scoreEngineConfig.style.getValue();
        config.difficultyLevel = scoreEngineConfig.difficulty.getValue();
        config.enabledDimensions = scoreEngineConfig.enabledDimensions;
        return config;
    }
    
    /**
     * 歌曲列表适配器
     */
    private class SongAdapter extends BaseAdapter {
        private Context context;
        private List<Song> songs;
        private LayoutInflater inflater;
        
        public SongAdapter(Context context, List<Song> songs) {
            this.context = context;
            this.songs = songs;
            this.inflater = LayoutInflater.from(context);
        }
        
        @Override
        public int getCount() {
            return songs.size();
        }
        
        @Override
        public Object getItem(int position) {
            return songs.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_song, parent, false);
                holder = new ViewHolder();
                holder.tvTitle = convertView.findViewById(R.id.tvTitle);
                holder.tvArtist = convertView.findViewById(R.id.tvArtist);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            
            Song song = songs.get(position);
            holder.tvTitle.setText(position + ". " + song.getTitle());
            holder.tvArtist.setText(song.getArtist());
            
            // 高亮选中的歌曲
            if (song.equals(selectedSong)) {
                holder.tvTitle.setTextColor(ContextCompat.getColor(context, R.color.green));
                holder.tvArtist.setTextColor(ContextCompat.getColor(context, R.color.green));
            } else {
                holder.tvTitle.setTextColor(ContextCompat.getColor(context, android.R.color.black));
                holder.tvArtist.setTextColor(ContextCompat.getColor(context, android.R.color.black));
            }
            
            return convertView;
        }
        
        class ViewHolder {
            TextView tvTitle;
            TextView tvArtist;
        }
    }
    
    /**
     * 请求必要的权限
     */
    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11及以上版本
            if (!Environment.isExternalStorageManager()) {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    startActivityForResult(intent, MANAGE_STORAGE_PERMISSION_REQUEST_CODE);
                } catch (Exception e) {
                    Toast.makeText(this, "请手动授予存储权限", Toast.LENGTH_LONG).show();
                }
            } else {
                requestOtherPermissions();
            }
        } else {
            // Android 10及以下版本
            requestOtherPermissions();
        }
    }

    /**
     * 请求其他权限（存储和录音）
     */
    private void requestOtherPermissions() {
        boolean allPermissionsGranted = true;
        
        // 检查每个权限是否已被授予
        for (String permission : PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }
        
        // 如果有权限未授予，请求所有权限
        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST_CODE);
        } else {
            Toast.makeText(this, "所有权限已获取", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MANAGE_STORAGE_PERMISSION_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    requestOtherPermissions();
                } else {
                    Toast.makeText(this, "需要存储权限才能使用应用", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            
            // 检查是否所有权限都被授予
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            if (allGranted) {
                Toast.makeText(this, "所有权限已获取", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "部分权限被拒绝，应用功能可能受限", Toast.LENGTH_LONG).show();
            }
        }
    }
}